<template>
  <div class="page-card">
    <div class="table-toolbar">
      <el-input
        v-model="search"
        placeholder="输入用户名或姓名搜索"
        clearable
        style="max-width: 260px"
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="openDialog()">
        <el-icon><Plus /></el-icon>
        开通账户
      </el-button>
    </div>

    <el-table :data="users" border v-loading="loading">
      <el-table-column prop="username" label="用户名" width="140" />
      <el-table-column prop="real_name" label="姓名" width="140" />
      <el-table-column prop="phone" label="手机号" width="150" />
      <el-table-column prop="email" label="邮箱" min-width="180" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openDialog(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :page-size="pagination.size"
        :current-page="pagination.page"
        :total="pagination.total"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="480px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="姓名" prop="real_name">
          <el-input v-model="form.real_name" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { createUser, deleteUser, getUserList, updateUser } from '@/api/system'
import type { User } from '@/types/system'

const loading = ref(false)
const users = ref<User[]>([])
const search = ref('')
const pagination = reactive({ page: 1, size: 10, total: 0 })

const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  id: 0,
  username: '',
  real_name: '',
  password: '',
  phone: '',
  email: '',
  status: 1
})

const rules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  real_name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const dialogTitle = computed(() => (isEdit.value ? '编辑账户' : '开通账户'))

const loadUsers = async () => {
  loading.value = true
  try {
    const keyword = search.value.trim().toLowerCase()
    const isSearching = !!keyword
    const limit = isSearching ? 500 : pagination.size
    const skip = isSearching ? 0 : (pagination.page - 1) * pagination.size
    const res = await getUserList({ skip, limit })
    users.value = isSearching
      ? res.items.filter(
          (item) =>
            item.username.toLowerCase().includes(keyword) ||
            item.real_name.toLowerCase().includes(keyword)
        )
      : res.items
    pagination.total = isSearching ? users.value.length : res.total
    if (isSearching) {
      pagination.page = 1
    }
  } catch (error: any) {
    ElMessage.error(error?.message || '加载账户失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadUsers()
}

const handleSearch = () => {
  pagination.page = 1
  loadUsers()
}

const resetForm = () => {
  Object.assign(form, {
    id: 0,
    username: '',
    real_name: '',
    password: '',
    phone: '',
    email: '',
    status: 1
  })
  formRef.value?.clearValidate()
}

const openDialog = (row?: User) => {
  resetForm()
  if (row) {
    isEdit.value = true
    Object.assign(form, row, { password: '' })
  } else {
    isEdit.value = false
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  saving.value = true
  try {
    if (isEdit.value) {
      await updateUser(form.id, {
        real_name: form.real_name,
        phone: form.phone,
        email: form.email,
        status: form.status,
        password: form.password || undefined
      })
    } else {
      await createUser({
        username: form.username,
        real_name: form.real_name,
        password: form.password,
        phone: form.phone,
        email: form.email,
        status: form.status
      })
    }
    ElMessage.success('操作成功')
    dialogVisible.value = false
    loadUsers()
  } catch (error: any) {
    ElMessage.error(error?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const handleDelete = async (row: User) => {
  await ElMessageBox.confirm(`确认删除账户【${row.real_name}】吗？`, '提示', {
    type: 'warning'
  })
  try {
    await deleteUser(row.id)
    ElMessage.success('已删除')
    loadUsers()
  } catch (error: any) {
    ElMessage.error(error?.message || '删除失败')
  }
}

onMounted(loadUsers)
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--spacing-md);
}
</style>
